package com.demo.filter;

import com.demo.utils.JwtUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

public class JWTAuthenFilter extends BasicAuthenticationFilter {

    private JwtUtils jwtUtils;

    //
    public JWTAuthenFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    //处理内部异常
    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String tokenHeader = request.getHeader(JwtUtils.TOKEN_HEADER);
        if (tokenHeader == null || !tokenHeader.startsWith(JwtUtils.TOKEN_PREFIX)) {
            //其中放行的方法为配置中的允许放行的方法
            chain.doFilter(request, response);
            return;
        }
        //解析Token，认证是否携带Token
        System.out.println("===========带前缀的Token=================");
        System.out.println(tokenHeader);
        String token = tokenHeader.replace(JwtUtils.TOKEN_PREFIX, "");
        System.out.println("============Token=============");
        System.out.println(token);
        jwtUtils=new JwtUtils();
        String username = jwtUtils.getUsernameFromToken(token);
        System.out.println("===========解析之后的用户是："+username+"===========================");
        Authentication authentication = new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        super.doFilterInternal(request, response, chain);
    }
}
